package org.jeecg.modules.kuawcsJs.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.hibernate.engine.jdbc.batch.spi.Batch;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.bzBaseinfo.entity.HqBzBaseinfo;
import org.jeecg.modules.bzBaseinfo.service.IHqBzBaseinfoService;
import org.jeecg.modules.kuawcsJs.entity.AgKuawcsJs;
import org.jeecg.modules.kuawcsJs.entity.FtpUtil;
import org.jeecg.modules.kuawcsJs.mapper.AgKuawcsJsMapper;
import org.jeecg.modules.kuawcsJs.service.IAgKuawcsJsService;
import org.jeecg.modules.renlmd.entity.HqStRenlmd;
import org.jeecg.modules.renlmd.entity.HqStRenlmdMx;
import org.jeecg.modules.renlmd.service.IHqStRenlmdMxService;
import org.jeecg.modules.renlmd.service.IHqStRenlmdService;
import org.jeecg.modules.shuibdb.entity.HqShuibdb;
import org.jeecg.modules.shuibdb.service.IHqShuibdbService;
import org.jeecg.modules.stCaip.entity.HqStCaip;
import org.jeecg.modules.stCaip.service.IHqStCaipService;
import org.jeecg.modules.yfRepair.entity.HqYfRepair;
import org.jeecg.modules.yfRepair.entity.HqYfRepairPiece;
import org.jeecg.modules.yfRepair.service.IHqYfRepairPieceService;
import org.jeecg.modules.yfRepair.service.IHqYfRepairService;
import org.jeecg.modules.zhinDg.entity.HqZhindg;
import org.jeecg.modules.zhinDg.service.IHqZhindgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 跨网传输接收
 * @Author: jeecg-boot
 * @Date:   2020-11-16
 * @Version: V1.0
 */
@Slf4j
@Service
public class AgKuawcsJsServiceImpl extends ServiceImpl<AgKuawcsJsMapper, AgKuawcsJs> implements IAgKuawcsJsService {


    @Autowired
    private IAgKuawcsJsService agKuawcsJsService;
    @Autowired
    private IHqShuibdbService hqShuibdbService;
    @Autowired
    private IHqZhindgService hqZhindgService;
    @Autowired
    private IHqBzBaseinfoService hqBzBaseinfoService;
    @Autowired
    private IHqStCaipService hqStCaipService;
    @Autowired
    private IHqYfRepairService hqYfRepairService;
    @Autowired
    private IHqYfRepairPieceService hqYfRepairPieceService;
    @Autowired
    private IHqStRenlmdService hqStRenlmdService;
    @Autowired
    private IHqStRenlmdMxService hqStRenlmdMxService;

    @Value("${kwakcs.savePath}")
    String savePath = "";

    @Value("${kwakcs.guangpnwIp}")
    String guangpnwIp= "";

    @Value("${kwakcs.username}")
    String username= "" ;

    @Value("${kwakcs.password}")
    String password= "";

    @Value("${kwakcs.port}")
    int port;



    /*
    二维码接收
     */

    @Override
    public Result<?> receiveFile(HttpServletRequest request, HttpServletResponse response) {
        log.info("跨网传输二维码接收开始"+DateUtils.formatDateTime());

        AgKuawcsJs agKuawcsJs = new AgKuawcsJs();
        agKuawcsJs.setJieskssj(new Date());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        ObjectMapper mapper = new ObjectMapper();
        String sysName = request.getParameter("sysName");
        String fileName = request.getParameter("fileName");

        Date d = new Date();
        String dateDir = new SimpleDateFormat("yyyy\\MM\\dd").format(d);
        String fileFullPath = savePath + File.separator + sysName + File.separator +dateDir+File.separator +fileName;
        InputStream in = null;
        FileOutputStream fos = null;
        String ret = "";
        try {
            in = request.getInputStream();
            File file = new File(savePath + File.separator + sysName+ File.separator+dateDir);
            if(!file.exists()){
                file.mkdirs();
            }
            fos = new FileOutputStream(fileFullPath);

          // fos= new OutputStreamWriter(new FileOutputStream(fileFullPath), "utf-8");

            ret = fileName;
            int size = 0;
            byte[] buffer = new byte[1024];
            while ((size = in.read(buffer,0,1024)) != -1) {
                fos.write(buffer, 0, size);
            }

            agKuawcsJs.setChuansfs("2");

            agKuawcsJs.setJieswjm(sysName);
            agKuawcsJs.setBaoclj(fileFullPath);
            agKuawcsJs.setDuqsj(new Date());




            //响应信息
            Map <String,Object> responseMap = new HashMap <String,Object>();
            responseMap.put("status", true);
            String jsonResponse = mapper.writeValueAsString(responseMap);
            sendResponse(jsonResponse,response,ret);
            ret = ret+"  "+"接收成功！";


        } catch (IOException e) {
            //响应信息
            Map<String,Object> responseMap = new HashMap <String,Object>();
            responseMap.put("status", false);
            responseMap.put("errorMsg", e.getMessage());
            String jsonResponse = "";
            try {
                jsonResponse = mapper.writeValueAsString(responseMap);
            } catch (JsonProcessingException e1) {
                ret = ret+"  "+"接收失败！";
                log.error("接收失败",e);

            }
            sendResponse(jsonResponse,response,ret);

        } finally{
            close(in, fos,ret);
            //移动文件到摆渡目录
        }

        agKuawcsJs.setJieswcsj(new Date());
        agKuawcsJsService.save(agKuawcsJs);

        //同步hq_shuibdb数据库
        if (fileName.endsWith("hq_shuibdb.json")) {
            syncShuibdb(fileName, fileFullPath);
        }
        //同步hq_zhindg数据库
        if (fileName.endsWith("hq_zhindg.json")) {
            syncZhindg(fileName, fileFullPath);
        }
        //同步hq_st_caip数据库
        if (fileName.endsWith("hq_st_caip.json")) {
            syncCaip(fileName, fileFullPath);
        }
        //同步hq_bz_baseinfo数据库
        if (fileName.endsWith("hq_bz_baseinfo.json")) {
            syncBz(fileName, fileFullPath);
        }
        //同步hq_yf_repair数据库
        if (fileName.endsWith("hq_yf_repair.json")) {
            syncYfRepair(fileName, fileFullPath);
        }
        //同步hq_yf_repair_piece数据库
        if (fileName.endsWith("hq_yf_repair_piece.json")) {
            syncYfRepairPiece(fileName, fileFullPath);
        }
        //同步hq_st_renlmd数据库
        if (fileName.endsWith("hq_st_renlmd.json")) {
            syncRenlmd(fileName, fileFullPath);
        }
        //同步hq_st_renlmd_mx数据库
        if (fileName.endsWith("hq_st_renlmd_mx.json")) {
            syncRenlmdMx(fileName, fileFullPath);
        }

        return null;
    }

    private void syncRenlmdMx(String fileName, String fileFullPath) {
        //同步hq_st_renlmd_mx数据库
        log.info("跨网传输接收开始，同步hq_st_renlmd_mx数据库" + DateUtils.formatDateTime());
        try {
            String s = ReadFile(fileFullPath);//获得json文件的内容

            List <HqStRenlmdMx> list=JSON.parseObject(s,new TypeReference<List <HqStRenlmdMx>>(){});



            for (HqStRenlmdMx hqStRenlmdMx:list
            ) {

                HqStRenlmdMx renlmdMx = hqStRenlmdMxService.getOne(new QueryWrapper <HqStRenlmdMx>().eq("id", hqStRenlmdMx.getId()));
                hqStRenlmdMx.setChuanswczt("1");
                if (renlmdMx!=null){
                    hqStRenlmdMxService.updateById(hqStRenlmdMx);
                }else {
                    hqStRenlmdMxService.save(hqStRenlmdMx);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void syncRenlmd(String fileName, String fileFullPath) {
        //同步hq_st_renlmd数据库
        log.info("跨网传输接收开始，同步hq_st_renlmd数据库" + DateUtils.formatDateTime());
        try {
            String s = ReadFile(fileFullPath);//获得json文件的内容

            List <HqStRenlmd> list=JSON.parseObject(s,new TypeReference<List <HqStRenlmd>>(){});



            for (HqStRenlmd hqStRenlmd:list
            ) {

                HqStRenlmd renlmd = hqStRenlmdService.getOne(new QueryWrapper <HqStRenlmd>().eq("id", hqStRenlmd.getId()));
                hqStRenlmd.setChuanswczt("1");
                if (renlmd!=null){
                    hqStRenlmdService.updateById(hqStRenlmd);
                }else {
                    hqStRenlmdService.save(hqStRenlmd);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void syncYfRepairPiece(String fileName, String fileFullPath) {
        //同步hq_yf_repair_piece数据库
        log.info("跨网传输接收开始，同步hq_yf_repair_piece数据库" + DateUtils.formatDateTime());
       // if (fileName.endsWith("hq_yf_repair_piece")){
            /*
             * 取出文件内容，填充对象
             */


            try {
                String s = ReadFile(fileFullPath);//获得json文件的内容

                List <HqYfRepairPiece> list=JSON.parseObject(s,new TypeReference<List <HqYfRepairPiece>>(){});



                for (HqYfRepairPiece hqYfRepairPiece:list
                ) {

                    HqYfRepairPiece yfRepairPiece = hqYfRepairPieceService.getOne(new QueryWrapper <HqYfRepairPiece>().eq("id", hqYfRepairPiece.getId()));
                    hqYfRepairPiece.setChuanswczt("1");
                    if (yfRepairPiece!=null){
                        hqYfRepairPieceService.updateById(hqYfRepairPiece);
                    }else {
                        hqYfRepairPieceService.save(hqYfRepairPiece);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        //}


    }

    private void syncYfRepair(String fileName, String fileFullPath) {
        //同步hq_yf_repair数据库
        log.info("跨网传输接收开始，同步hq_yf_repair数据库" + DateUtils.formatDateTime());
     //   if (fileName.endsWith("hq_yf_repair")){
            /*
             * 取出文件内容，填充对象
             */


            try {
                String s = ReadFile(fileFullPath);//获得json文件的内容


                List <HqYfRepair> list=JSON.parseObject(s,new TypeReference<List <HqYfRepair>>(){});



                for (HqYfRepair hqYfRepair:list
                ) {

                    HqYfRepair yfRepair = hqYfRepairService.getOne(new QueryWrapper <HqYfRepair>().eq("id", hqYfRepair.getId()));
                    hqYfRepair.setChuanswczt("1");
                    if (yfRepair!=null){
                        hqYfRepairService.updateById(hqYfRepair);
                    }else {
                        hqYfRepairService.save(hqYfRepair);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

       // }


    }

    private void syncBz(String fileName, String fileFullPath) {
        //同步hq_bz_baseinfo数据库
        log.info("跨网传输接收开始，同步hq_bz_baseinfo数据库" + DateUtils.formatDateTime());
     //   if (fileName.endsWith("hq_bz_baseinfo")){
            /*
             * 取出文件内容，填充对象
             */


            try {
                String s = ReadFile(fileFullPath);//获得json文件的内容

                List <HqBzBaseinfo> list=JSON.parseObject(s,new TypeReference<List <HqBzBaseinfo>>(){});



                for (HqBzBaseinfo hqBzBaseinfo:list
                ) {

                    HqBzBaseinfo bzBaseinfo = hqBzBaseinfoService.getOne(new QueryWrapper <HqBzBaseinfo>().eq("id", hqBzBaseinfo.getId()));
                    hqBzBaseinfo.setChuanswczt("1");
                    if (bzBaseinfo!=null){
                        hqBzBaseinfoService.updateById(hqBzBaseinfo);
                    }else {
                        hqBzBaseinfoService.save(hqBzBaseinfo);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

       // }

    }

    private void syncCaip(String fileName, String fileFullPath) {
//同步hq_st_caip数据库
        log.info("跨网传输接收开始，同步hq_st_caip数据库" + DateUtils.formatDateTime());
      //  if (fileName.endsWith("hq_st_caip")){
            /*
             * 取出文件内容，填充对象
             */


            try {
                String s = ReadFile(fileFullPath);//获得json文件的内容

                List <HqStCaip> list=JSON.parseObject(s,new TypeReference<List <HqStCaip>>(){});



                for (HqStCaip hqStCaip:list
                ) {

                    HqStCaip caip = hqStCaipService.getOne(new QueryWrapper <HqStCaip>().eq("id",hqStCaip.getId()));
                    hqStCaip.setChuanswczt("1");
                    if (caip!=null){
                        hqStCaipService.updateById(hqStCaip);
                    }else {
                        hqStCaipService.save(hqStCaip);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

    //    }

    }


    private void syncZhindg(String fileName, String fileFullPath) {
        //同步hq_zhindg数据库
        log.info("跨网传输接收开始，同步hq_zhindg数据库" + DateUtils.formatDateTime());
       // if (fileName.endsWith("hq_zhindg.json")){
            /*
             * 取出文件内容，填充对象
             */
            try {

                String s = ReadFile(fileFullPath);//获得json文件的内容

                List <HqZhindg> list=JSON.parseObject(s,new TypeReference<List <HqZhindg>>(){});

                for (HqZhindg hqZhindg:list
                ) {

                    HqZhindg zhindg = hqZhindgService.getOne(new QueryWrapper <HqZhindg>().eq("id", hqZhindg.getId()));
                    hqZhindg.setChuanswczt("1");
                    if (zhindg!=null){
                        hqZhindgService.updateById(hqZhindg);
                    }else {
                        hqZhindgService.save(hqZhindg);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

       // }

    }

    private void syncShuibdb(String fileName,String fileFullPath) {
        log.info("跨网传输接收开始，同步hq_shuibdb数据库" + DateUtils.formatDateTime());
        //同步hq_shuibdb数据库
    //    if (fileName.endsWith("hq_shuibdb.json")){
            /*
             * 取出文件内容，填充对象
             */
            try {

                String s = ReadFile(fileFullPath);//获得json文件的内容

                List <HqShuibdb> list = JSON.parseObject(s, new TypeReference <List <HqShuibdb>>() {
                });

                for (HqShuibdb hqShuibdb : list
                ) {

                    HqShuibdb shuibdb = hqShuibdbService.getOne(new QueryWrapper <HqShuibdb>().eq("id", hqShuibdb.getId()));
                    hqShuibdb.setChuanswczt("1");
                    if (shuibdb != null) {
                        hqShuibdbService.updateById(hqShuibdb);
                    } else {
                        hqShuibdbService.save(hqShuibdb);
                    }
                }
            } catch(Exception e){
                e.printStackTrace();
            }

      //  }

    }

    //读文件，返回字符串
    public String ReadFile(String path){
        File file = new File(path);
        BufferedReader reader = null;
        String laststr = "";

        try {
            //System.out.println("以行为单位读取文件内容，一次读一整行：");
            //reader = new BufferedReader(new FileReader(file));
            reader =   new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));
            String tempString = null;

            //一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                //显示行号
                laststr = laststr +tempString;

            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return laststr;
    }

    /**
     * 关闭流
     */
    private void close(InputStream in,FileOutputStream fos,String ret) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            if(in != null){
                in.close();
            }
            if(fos != null){
                fos.close();
            }
        } catch (IOException e) {
            ret = ret+"  "+"接收失败！";

            log.error("接收失败",e);
        }
    }

    /**
     * 返回响应
     */
    private void sendResponse(String responseString,HttpServletResponse response,String ret){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter pw = null;
        try {
            pw = response.getWriter();
            pw.write(responseString);
            pw.flush();
        } catch (IOException e) {
            ret = ret+"  "+"响应消息发送失败！";

            log.error("响应消息发送失败",e);
        }finally {
            IOUtils.closeQuietly(pw);
        }
    }

    /*
    光盘接收
     */
    @Override
    public Result <?> receive(HttpServletRequest request, HttpServletResponse response) {
        log.info("跨网传输光盘接收开始"+DateUtils.formatDateTime());
        //request参数传的目录
        String path=request.getParameter("ftpFilePath");
        log.info(request.getParameter("ftpFilePath"));


        AgKuawcsJs agKuawcsJs = new AgKuawcsJs();
        agKuawcsJs.setJieskssj(new Date());
        int num;
        if (path.contains("houqin_guangpan")){
            agKuawcsJs.setJieswjm(path.substring(path.indexOf("houqin_guangpan")));
            num=path.indexOf("houqin_guangpan")-1;
        }else{
            agKuawcsJs.setJieswjm(path.substring(path.indexOf("houqin_guangpan")));
            num=path.indexOf("Rx")-1;
        }

        FtpUtil ftp = new FtpUtil(username,password, guangpnwIp,port);


        try {
            //下载
            String ftpFilePath="/home/admin"+path.substring(0,num);
            ftp.down(ftpFilePath,savePath);


            agKuawcsJs.setChuansfs("1");
            agKuawcsJs.setJieswcsj(new Date());
            agKuawcsJs.setJieswjm(path);
            agKuawcsJs.setBaoclj(savePath);
            agKuawcsJs.setDuqsj(new Date());
            agKuawcsJsService.save(agKuawcsJs);


        } catch (IOException e) {
            e.printStackTrace();
            Result.error("接收文件失败！");

        }

        return Result.ok("接收文件成功!");

    }


}
